package www.tensquare.com.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.tensquare.tensquare_common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {

    @Autowired
    private JwtUtil jwtUtil;


    /**
     *设置过滤的类型
     * pre前置过滤
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器的执行顺序，数字越小优先执行
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     * 当前过滤器是否开启
     * false 关闭
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器内执行的操作 return 任何object的值都表示继续执行
     * setsendzuulResponse(false) 表示不再继续执行
     * @return
     * @throws ZuulException
     */

    @Override
    public Object run() throws ZuulException {
        System.out.println("经过后台过滤器了");
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request =currentContext.getRequest();
        if(request.getMethod().equals("OPTIONS"))
        {
            return null;
        }
        if(request.getRequestURI().indexOf("login")>0)
        {
            return null;
        }
        String header = request.getHeader("Authorization");
        if(header!=null && !"".equals(header))
        {
            if(header.startsWith("Bearer "))
            {
                String token=header.substring(7);
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String)claims.get("roles");
                    if(roles.equals("admin"))
                    {
                        //表示把头信息转发，并且放行
                        currentContext.addZuulRequestHeader("Authorization",header);
                        return  null;
                    }
                }catch(Exception e){
                    e.printStackTrace();
                    currentContext.setSendZuulResponse(false);//终止运行
                    currentContext.setResponseStatusCode(403);
                    currentContext.setResponseBody("权限不足");
                    currentContext.getResponse().setContentType("text/html;charset=utf-8");
                }
            }
        }
        return null;
    }
}
